package c_leetcode.a_56_merge_intervals;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;

/**
 * 遍历 - 两层
 *
 * @author He Kuntao
 * @since 2025/3/14 13:35
 */
public class Foreach {
    public static void main(String[] args) {
        System.out.println(Arrays.deepToString(new Foreach().merge(new int[][]{{1, 3}, {2, 6}, {8, 10}, {15, 18}})));
    }


    public int[][] merge(int[][] intervals) {
        // 左端点排序
        Arrays.sort(intervals, Comparator.comparingInt(o -> o[0]));
        // 结果集
        ArrayList<int[]> result = new ArrayList<>();

        for (int i = 0; i < intervals.length; i++) {
            int right = intervals[i][1];
            int to = 0;
            for (int j = i + 1; j < intervals.length; j++) {
                if (intervals[j][0] > right) {
                    break;
                }else {
                    right = Math.max(right, intervals[j][1]);
                    to++;
                }
            }
            result.add(new int[]{intervals[i][0], right});
            i += to;
        }
        return result.toArray(new int[result.size()][]);
    }
}
